package com.wjf.birdfish.util.md5;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 计算文件的MD5
 */
public class FileMD5 {
	protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	protected static MessageDigest messageDigest = null;
	static {
		try {
			messageDigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	public static boolean md5Equals(String md5, String fileName) {
		if (md5 == null || fileName == null) {
			return false;
		}
		String source = null;
		try {
			source = getFileMD5String(fileName);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return md5.equals(source);

	}

	/**
	 * 计算文件的MD5
	 * 
	 * @param fileName
	 *            文件的绝对路径
	 * @return
	 * @throws IOException
	 */
	public static String getFileMD5String(String fileName) throws IOException {
		File f = new File(fileName);
		if (f.isFile()) {
			return getFileMD5String(f);
		} else {
			
			File[] files = f.listFiles();
			List<File> filesSort = new ArrayList<File>(files.length);
			for(File tmp : files){
				filesSort.add(tmp);
			}
			Collections.sort(filesSort);
			return getFileMD5String(filesSort);
		}

	}

	/**
	 * 计算文件的MD5，重载方法
	 * 
	 * @param file
	 *            文件对象
	 * @return
	 * @throws IOException
	 */
	public static String getFileMD5String(File file) throws IOException {
		FileInputStream in = new FileInputStream(file);
		FileChannel ch = in.getChannel();
		MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
				file.length());
		messageDigest.update(byteBuffer);
		return bufferToHex(messageDigest.digest());
	}

	public static String getFileMD5String(List<File> files) throws IOException {
		StringBuffer sb = new StringBuffer();
		for (File file : files) {
			FileInputStream in = new FileInputStream(file);
			FileChannel ch = in.getChannel();
			MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY,
					0, file.length());
			messageDigest.update(byteBuffer);
			sb.append(bufferToHex(messageDigest.digest()));
		}
		return sb.toString();
	}

	private static String bufferToHex(byte bytes[]) {
		return bufferToHex(bytes, 0, bytes.length);
	}

	private static String bufferToHex(byte bytes[], int m, int n) {
		StringBuffer stringbuffer = new StringBuffer(2 * n);
		int k = m + n;
		for (int l = m; l < k; l++) {
			appendHexPair(bytes[l], stringbuffer);
		}
		return stringbuffer.toString();
	}

	private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
		char c0 = hexDigits[(bt & 0xf0) >> 4];
		char c1 = hexDigits[bt & 0xf];
		stringbuffer.append(c0);
		stringbuffer.append(c1);
	}

	public static void main(String[] args){
		if (args.length != 2) {
			System.err.printf("Usage: %s [generic options] <compare> <filePath>\n",	FileMD5.class.getSimpleName());
			System.exit(0);
		}
		
		System.out.println(md5Equals(args[0], args[1]));
		
//		 long start = System.currentTimeMillis();
//		
//		 String fileName1 = "C:\\log1.rar";
//		 String fileName2 = "C:\\log2.rar";
//		 String fileName3 = "C:\\log3.rar";
//		 String fileName4 = "F:\\srm_tmp\\upload\\valid\\ApplySer\\META-INF";
//		 String fileName5 = "F:\\srm_tmp\\upload\\valid\\ApplySer2\\META-INF";
//		 String md5Value1 = getFileMD5String(fileName1);
//		 String md5Value2 = getFileMD5String(fileName2);
//		 String md5Value3 = getFileMD5String(fileName3);
//				
//		 String md5Value4 = getFileMD5String(fileName4);
//		 String md5Value5 = getFileMD5String(fileName5);
//		
//		 System.out.println(md5Value1.equals(md5Value2));
//		 System.out.println(md5Value1.equals(md5Value3));
//				
//		 System.out.println(md5Value4);
//		 
//		 System.out.println(md5Value4.equals(md5Value5));
//		
//		 long end = System.currentTimeMillis();
//		 System.out.println("Consume " + (end - start) + "ms");

	}
}